package com.accgm.api.oauth;

import org.json.JSONException;
import org.json.JSONML;
import org.json.JSONObject;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.routing.Filter;

public class BaseFilter extends Filter {
    protected MediaType mediaType = MediaType.APPLICATION_JSON;

    protected int beforeHandle(Request request, Response response) {
	String format = (String) request.getAttributes().get("format");
	if (format.equalsIgnoreCase("xml")) {
	    mediaType = MediaType.APPLICATION_XML;
	}
	return CONTINUE;
    }

    /**
     * 非法access token
     * 
     * @param type
     * @return
     */
    protected Representation invalidAccessToken(MediaType type) {
	try {
	    Representation r = null;
	    JSONObject json = new JSONObject();
	    json.put("error_code", 52);
	    json.put("error_description", "OAuth - invalid access token");
	    r = new StringRepresentation(json.toString(),
		    MediaType.APPLICATION_JSON);
	    if (type.equals(MediaType.APPLICATION_JSON)) {
		return r;
	    } else {
		String jsonXML = JSONML.toString(json);
		r = new StringRepresentation(jsonXML, MediaType.APPLICATION_XML);
		return r;
	    }
	} catch (JSONException e) {
	    return null;
	}
    }

    /**
     * 签名失败
     * 
     * @param type
     * @return
     */
    protected Representation invalidSignature(MediaType type) {
	try {
	    Representation r = null;
	    JSONObject json = new JSONObject();
	    json.put("error_code", 60);
	    json.put("error_description", "OAuth - signature failed");
	    r = new StringRepresentation(json.toString(),
		    MediaType.APPLICATION_JSON);
	    if (type.equals(MediaType.APPLICATION_JSON)) {
		return r;
	    } else {
		String jsonXML = JSONML.toString(json);
		r = new StringRepresentation(jsonXML, MediaType.APPLICATION_XML);
		return r;
	    }
	} catch (JSONException e) {
	    return null;
	}
    }

    /**
     * 未知app
     * 
     * @param type
     * @return
     */
    protected Representation unknownApp(MediaType type) {
	try {
	    Representation r = null;
	    JSONObject json = new JSONObject();
	    json.put("error_code", 53);
	    json.put("error_description", "OAuth – unknown application");
	    r = new StringRepresentation(json.toString(),
		    MediaType.APPLICATION_JSON);
	    if (type.equals(MediaType.APPLICATION_JSON)) {
		return r;
	    } else {
		String jsonXML = JSONML.toString(json);
		r = new StringRepresentation(jsonXML, MediaType.APPLICATION_XML);
		return r;
	    }
	} catch (JSONException e) {
	    return null;
	}
    }
}
